import React, { useState, useEffect, useRef, useMemo } from 'react';
import { Carousel, Calendar, Button, Radio, DatePicker, ConfigProvider } from 'antd';
import Formattime from './formattime'
import './frame.css'
import Statis from './statis'
import Charts from './charts'
import Cost from './cost'
import dayjs, { Dayjs } from 'dayjs';
import io, { Socket } from 'socket.io-client';
import moment from 'moment';
import type { RadioChangeEvent, DatePickerProps } from 'antd';
import _ from 'lodash';
type Message = any;
import zhCN from 'antd/es/locale/zh_CN';
type MedicalData = {
    ols: Array<{ [key: string]: any }>;
    pls: Array<{ [key: string]: any }>;
    sls: Array<{ [key: string]: any }>;
    gls: Array<{ [key: string]: any }>;
};
const Home: React.FC = () => {
    ///走马灯图片
    const imgs = [
        { title: '产后抑郁症的诊断与治疗', img: '/wjimgs/3-1.jpg' },
        { title: '甲状腺的核素治疗', img: '/wjimgs/3-2.jpg' },
        { title: '同步化疗在胃癌治疗中的价值', img: '/wjimgs/3-3.jpg' }
    ]
    ///走马灯图片
    ///////////////////////知识栏目
    const kls = [
        { title: '产后抑郁症的诊断和治疗', cont: '四川省测试中心医院', name: '李医生' },
        { title: '甲状腺的核素治疗', cont: '四川省第二测试医院', name: '刘医生' },
        { title: '同步化疗在胃癌治疗中的价值', cont: '中国测试医科医院', name: '刘医生' },
        { title: '妊娠合并糖尿病的规范化诊断与治疗', cont: '四川省第二测试医院', name: '刘医生' },
        { title: '更年期综合征的临床诊断及治疗', cont: '四川省第二测试医院', name: '刘医生' },
    ]
    ///////////////////////知识栏目
    ///////////公告栏目
    const gls = [
        { title: '请注意单位注意月底绩效管理', date: '06-12' },
        { title: '请注意单位注意月底绩效管理', date: '06-12' },
        { title: '06-10系统维护通知', date: '06-10' },
        { title: '05-10系统维护通知', date: '05-10' },
        { title: '04-10系统维护通知', date: '04-10' },
        { title: '03-10系统维护通知', date: '03-10' },
        { title: '02-10系统维护通知', date: '02-10' },
        { title: '01-10系统维护通知', date: '01-10' },
    ]
    ///////////公告栏目
    /////////////////////////日历
    const headerRender = ({ value, type, onChange }: { value: Dayjs, type: string, onChange: (newValue: Dayjs) => void }) => {
        const month = value.month();  // 获取当前月份
        const year = value.year();    // 获取当前年份

        const monthNames = ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"];

        return (
            <div style={{ fontSize: '17px', justifyContent: 'space-between', display: 'flex', padding: 10, textAlign: 'center' }}>
                <div>
                    {year}年{monthNames[month]}
                </div>
                <div style={{ width: '50%', display: 'flex', justifyContent: 'space-evenly' }}>
                    <Button onClick={() => onChange(value.clone().subtract(1, 'month'))}>上一月</Button>

                    <Button onClick={() => onChange(value.clone().add(1, 'month'))}>下一月</Button>
                    <Button onClick={() => onChange(value.clone().add(1, 'month'))}>下一月</Button>
                </div>

            </div>
        );
    };
    /////////////////////////日历
    //////////////////////////////后端数据返回///////////////////////
    const [ols, setols] = useState([])//接诊表
    const [pls, setpls] = useState([])//处方表
    const [sls, setsls] = useState([])//手术表
    const [glls, setglls] = useState([])//会诊表
    ///计算门诊总人数
    // const processedData = useMemo(() => {
    //     console.log("计算数据...");
    //     return data.map(item => item * 2); // 假设我们需要处理数据
    //   }, [data]); // 只有当 `data` 改变时才重新计算
    const [formatting, setformatting] = useState('YYYY-MM-DD')
    const handleoldnums = useMemo(() => {
        let monay = 0
        // 获取当前日期
        let today: Date = new Date();

        // 创建昨天的日期对象
        let yesterday: Date = new Date(today);
        yesterday.setDate(today.getDate() - 1);
        const nums = ols.filter((item: any) => {
            return new Date(item.date).getFullYear() === yesterday.getFullYear() &&
                new Date(item.date).getMonth() === yesterday.getMonth() &&
                new Date(item.date).getDate() === yesterday.getDate();
        })
        nums.forEach((item: any) => {
            monay += item.regfee
        })
        const truenums = nums.filter((item: any) => {
            return item.clinical
        })
        const falsenums = nums.filter((item: any) => {
            return !item.clinical
        })
        return { monay: monay, nums: nums.length, truenums: truenums.length, falsenums: falsenums.length }
    }, [ols])
    const handlenums = useMemo(() => {
        let monay = 0
        let datetime = new Date()
        const nums = ols.filter((item: any) => {
            return new Date(item.date).getFullYear() === datetime.getFullYear() &&
                new Date(item.date).getMonth() === datetime.getMonth() &&
                new Date(item.date).getDate() === datetime.getDate();
        })
        nums.forEach((item: any) => {
            monay += item.regfee
        })
        const truenums = nums.filter((item: any) => {
            return item.clinical
        })
        const falsenums = nums.filter((item: any) => {
            return !item.clinical
        })
        return { monay: monay, nums: nums.length, truenums: truenums.length, falsenums: falsenums.length }
    }, [ols])
    //////////医疗数据面板/////////
    const options = [
        {
            label: '日',
            value: 'YYYY-MM-DD',
        },
        {
            label: '月',
            value: 'YYYY-MM',
        },
        {
            label: '年',
            value: 'YYYY',
        },
    ];
    const [checktime, setchecktime] = useState(new Date())
    const handlecharts = useMemo(() => {
        const currentDate = moment(checktime); // 获取当前时间
        const formattedDate = currentDate.format(formatting); // 格式化时间
        const olist = ols.filter((item: any) => {
            return moment(item.date).format(formatting) == formattedDate
        })
        const plist = pls.filter((item: any) => {
            return moment(item.date).format(formatting) == formattedDate
        })
        const slist = sls.filter((item: any) => {
            return moment(item.date).format(formatting) == formattedDate
        })
        const glist = glls.filter((item: any) => {
            return moment(item.date).format(formatting) == formattedDate
        })

        return { olist: olist, plist: plist, slist: slist, glist: glist }
    }, [ols, pls, sls, glls, formatting, checktime])
    const [checkdate, setcheckdate] = useState('date')
    const onChange = ({ target: { value } }: RadioChangeEvent) => {
        if (value == 'YYYY') {
            setcheckdate('year')
        }
        if (value == 'YYYY-MM') {
            setcheckdate('month')
        }
        if (value == 'YYYY-MM-DD') {
            setcheckdate('date')
        }
        setformatting(value);
    };
    const onChangedate: DatePickerProps['onChange'] = (date, dateString) => {
        setchecktime(new Date(date.toISOString()))
    };
    /////////医疗数据面板/////////


    //////-----费用计算------////////
    const handlemonay = useMemo(() => {
        let olss = ols.sort((a: any, b: any) => new Date(a.date).getTime() - new Date(b.date).getTime())
        let plss = pls.sort((a: any, b: any) => new Date(a.date).getTime() - new Date(b.date).getTime())
        // const currentDate = new Date().getTime() - 1 * 24 * 60 * 60 * 1000// 获取当前时间
        const currentDate = moment(new Date());
        const formattedDate = currentDate.format('YYYY-MM-DD');
        olss = olss.filter((item: any) => {
            return moment(item.date).format('YYYY-MM-DD') == formattedDate
        })
        plss = plss.filter((item: any) => {
            return moment(item.date).format('YYYY-MM-DD') == formattedDate
        })
        let exe = 0//检查
        let che = 0//检验
        let pre = 0//处方
        olss.forEach((item: any) => {
            exe += item.examnum
        })
        olss.forEach((item: any) => {
            che += item.testnum
        })
        plss.forEach((item: any) => {
            pre += item.price
        })
        return { exe: exe, che: che, pre: pre, all: exe + che + pre }
    }, [ols, pls])
    const handleoldmonay = useMemo(() => {
        let olss = ols.sort((a: any, b: any) => new Date(a.date).getTime() - new Date(b.date).getTime())
        let plss = pls.sort((a: any, b: any) => new Date(a.date).getTime() - new Date(b.date).getTime())
        // const currentDate = new Date().getTime() - 1 * 24 * 60 * 60 * 1000// 获取当前时间
        const currentDate = moment(new Date());
        const formattedDate = currentDate.subtract(1, 'days').format('YYYY-MM-DD');
        olss = olss.filter((item: any) => {
            return moment(item.date).format('YYYY-MM-DD') == formattedDate
        })
        plss = plss.filter((item: any) => {
            return moment(item.date).format('YYYY-MM-DD') == formattedDate
        })
        let exe = 0//检查
        let che = 0//检验
        let pre = 0//处方
        olss.forEach((item: any) => {
            exe += item.examnum
        })
        olss.forEach((item: any) => {
            che += item.testnum
        })
        plss.forEach((item: any) => {
            pre += item.price
        })
        return { exe: exe, che: che, pre: pre, all: exe + che + pre }
    }, [ols, pls])
    //////-----费用计算------////////
    //////////////////////////////后端数据返回/////////////////////////
    ////////////////////////////////////////WebSocket/////////////////////////////////
    // 定义 messages 为 string 数组
    const [messages, setMessages] = useState<Message[]>([]);
    // 定义 socket 的类型为 Socket | null
    const [socket, setSocket] = useState<Socket | null>(null);
    const [items, setItems] = useState<any>({});
    // 递归函数对比两个对象中的 _id 是否相等
    type NestedObject = { [key: string]: unknown };

    function compareNestedIds(a: unknown, b: unknown): boolean {
        // 处理基础类型直接比较
        if (typeof a !== typeof b) return false;
        if (a === null || b === null) return a === b;

        // 处理数组类型
        if (Array.isArray(a) && Array.isArray(b)) {
            if (a.length !== b.length) return false;
            return a.every((item, index) => compareNestedIds(item, b[index]));
        }

        // 处理对象类型
        if (typeof a === 'object' && typeof b === 'object') {
            const objA = a as NestedObject;
            const objB = b as NestedObject;

            // 检查 _id 属性
            if (objA._id !== undefined && objB._id !== undefined) {
                if (objA._id !== objB._id) return false;
            } else if (objA._id !== objB._id) { // 处理一个存在一个不存在的情况
                return false;
            }

            // 合并所有唯一键
            const keys = new Set([...Object.keys(objA), ...Object.keys(objB)]);
            for (const key of keys) {
                if (!compareNestedIds(objA[key], objB[key])) return false;
            }
            return true;
        }

        // 处理基础类型值比较
        return a === b;
    }
    useEffect(() => {
        // 连接到后端 Socket.IO 服务器
        const socketConnection = io('http://localhost:3003');

        // 监听 'items' 事件，接收服务器发送的数据

        socketConnection.on('items', (receivedItems: any) => {
            if (!compareNestedIds(items, receivedItems)) {
                setTimeout(() => {
                    setItems(receivedItems);
                    setols(receivedItems.ols);
                    setpls(receivedItems.pls);
                    setsls(receivedItems.sls);
                }, 0);
            }
        });
        // 监听服务器发送的消息
        socketConnection.on('message', (message: Message) => {
            setMessages(message);
        });
        setSocket(socketConnection);


        // 清理连接
        return () => {
            if (socketConnection) {
                socketConnection.disconnect();
            }
        };
    }, []);


    // 通过 API 获取数据

    ////////////////////////////////////////WebSocket/////////////////////////////////
    return (
        <>
            {/* <Button onClick={() => {
                console.log(items);
            }}>打印</Button> */}
            <div style={{ display: 'flex', justifyContent: 'space-between', margin: 'auto', width: '2132px', height: '1320px' }}>
                <div style={{ width: '1530px', display: 'flex', flexDirection: 'column', justifyContent: 'space-between' }}>
                    <div style={{ display: 'flex', background: 'white', width: '100%', height: '270px' }}>
                        <Statis title={'今日门诊总人数'} img={'/wjimgs/two.png'} num={handlenums.nums} unit={'人'} cont={handlenums.nums - handleoldnums.nums}></Statis>
                        <Statis title={'今日挂号金额'} img={'/wjimgs/money.png'} num={handlenums.monay} unit={'元'} cont={handlenums.monay - handleoldnums.monay}></Statis>
                        <Statis title={'今日待接诊人数'} img={'/wjimgs/two.png'} num={handlenums.truenums} unit={'人'} cont={handlenums.truenums - handleoldnums.truenums}></Statis>
                        <Statis title={'今日已接诊人数'} img={'/wjimgs/two.png'} num={handlenums.falsenums} unit={'人'} cont={handlenums.falsenums - handleoldnums.falsenums}></Statis>
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%', height: '530px' }}>
                        <div style={{ background: 'white', width: '400px', height: '100%' }}>
                            <div style={{ borderBottom: '2px solid rgb(240,240,240)', height: '12%', display: 'flex', alignItems: 'center', padding: '20px' }}>
                                <h2>我常用的功能</h2>
                            </div>
                            <div style={{ marginTop: '20px', width: '100%', display: 'flex' }}>
                                <div style={{ width: '33.33%', textAlign: 'center', }}>
                                    <img src="/wjimgs/2-1.png" style={{ width: '40%' }} />
                                    <p>医生工作台</p>
                                </div>
                                <div style={{ width: '33.33%', textAlign: 'center', }}>
                                    <img src="/wjimgs/2-2.png" style={{ width: '40%' }} />
                                    <p>患者就诊查询</p>
                                </div>
                                <div style={{ width: '33.33%', textAlign: 'center', }}>
                                    <img src="/wjimgs/2-3.png" style={{ width: '40%' }} />
                                    <p>协定处方管理</p>
                                </div>

                            </div>


                        </div>
                        <div style={{ background: 'white', flexWrap: 'wrap', display: 'flex', width: '1115px', height: '100%' }}>

                            <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px', width: '100%', height: '12%', border: '1px solid rgb(240,240,240)' }}>
                                <h2>医疗数据面板</h2>
                                <div style={{ display: 'flex', fontSize: '20px' }}>
                                    <span>时间类型：</span>
                                    <Radio.Group value={formatting} onChange={onChange} size="large" options={options} defaultValue="YYYY-MM-DD" optionType="button" />
                                    <ConfigProvider locale={zhCN}>
                                        <DatePicker style={{ display: checkdate == 'date' ? '' : 'none' }} size={'large'} value={dayjs(checktime)} onChange={onChangedate} picker='date' />
                                        <DatePicker style={{ display: checkdate == 'month' ? '' : 'none' }} size={'large'} value={dayjs(checktime)} onChange={onChangedate} picker='month' />
                                        <DatePicker style={{ display: checkdate == 'year' ? '' : 'none' }} size={'large'} value={dayjs(checktime)} onChange={onChangedate} picker='year' />
                                    </ConfigProvider>
                                </div>
                            </div>
                            <Charts title={'接诊人数'} data={handlecharts.olist} truecon='初诊' falsecon='复诊' field={'numtime'} colors={['#18ccd0', '#0468ff']}></Charts>
                            <Charts title={'处方人数'} data={handlecharts.plist} truecon='西药' falsecon='中药' field={'drug'} colors={['#faad14', '#fa541c']}></Charts>
                            <Charts title={'检查人数'} data={handlecharts.olist} truecon='初诊' falsecon='复诊' field={'exam'} colors={['#18ccd0', '#0468ff']}></Charts>
                            <Charts title={'检验人数'} data={handlecharts.olist} truecon='初诊' falsecon='复诊' field={'test'} colors={['#18ccd0', '#0468ff']}></Charts>
                            <Charts title={'入院证人数'} data={handlecharts.olist} truecon='初诊' falsecon='复诊' field={'reside'} colors={['#18ccd0', '#0468ff']}></Charts>
                            <Charts title={'医嘱处置人数'} data={handlecharts.olist} truecon='初诊' falsecon='复诊' field={'drug'} colors={['#18ccd0', '#0468ff']}></Charts>
                            <Charts title={'手术人数'} data={handlecharts.slist} truecon='门诊' falsecon='住院' field={'outp'} colors={['#18ccd0', '#a0d911']}></Charts>
                            <Charts title={'会诊人数'} data={handlecharts.glist} truecon='线上' falsecon='线下' field={'grou'} colors={['#9254de', '#1677ff']}></Charts>
                            <Cost title={'门诊总费用（元）'} newmonay={handlemonay.all} oldmonay={handleoldmonay.all}></Cost>
                            <Cost title={'处方费用（元）'} newmonay={handlemonay.pre} oldmonay={handleoldmonay.pre}></Cost>
                            <Cost title={'检查费用（元）'} newmonay={handlemonay.exe} oldmonay={handleoldmonay.exe}></Cost>
                            <Cost title={'检验费用（元）'} newmonay={handlemonay.che} oldmonay={handleoldmonay.che}></Cost>
                        </div>
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between', width: '100%', height: '490px' }}>
                        <div style={{ background: 'white', width: '1130px', height: '100%' }}>
                            <div style={{ justifyContent: 'space-between', borderBottom: '2px solid rgb(240,240,240)', height: '12%', display: 'flex', alignItems: 'center', padding: '20px' }}>
                                <h2>知识栏目</h2>
                                <div style={{ fontSize: '20px', color: 'gray' }}>更多</div>
                            </div>
                            <div style={{ display: 'flex', height: '88%' }}>
                                <div style={{ padding: '20px', width: '65%', height: '100%' }}>
                                    <Carousel style={{ position: 'relative', background: 'blue', width: '100%', height: '390px' }} autoplay arrows infinite={true}
                                        dots
                                    >
                                        {
                                            imgs.map((item, index) => {
                                                return (
                                                    <div key={index}>
                                                        <div style={{ color: 'white', position: 'absolute', top: '0', width: '100%', background: 'rgba(0,0,0,0.3)', fontSize: '20px' }}>{item.title}</div>
                                                        <img
                                                            src={item.img}
                                                            style={{ objectFit: 'cover', height: '390px', width: '100%' }}
                                                        />
                                                    </div>
                                                )
                                            })
                                        }


                                    </Carousel>
                                </div>
                                <div style={{ lineHeight: '33px', width: '35%', height: '100%' }}>

                                    <ul>
                                        {
                                            kls.map((item, index) => {
                                                return (
                                                    <li key={index}>
                                                        <h2><span style={{ marginRight: '10px', display: 'inline-block', borderRadius: '50%', background: '#0468ff', height: '20px', width: '20px' }}></span>{item.title}</h2>
                                                        <p style={{ textIndent: '30px', }}><span>{item.cont}</span>&nbsp;&nbsp;<span>{item.name}</span></p>
                                                    </li>
                                                )
                                            })
                                        }

                                    </ul>
                                </div>
                            </div>
                        </div>
                        <div style={{ background: 'white', width: '370px', height: '100%' }}>
                            <div style={{ justifyContent: 'space-between', borderBottom: '2px solid rgb(240,240,240)', height: '12%', display: 'flex', alignItems: 'center', padding: '20px' }}>
                                <h2>公告栏目</h2>
                                <div style={{ fontSize: '20px', color: 'gray' }}>更多</div>
                            </div>
                            <div style={{ width: '100%', fontSize: '20px', padding: '20px', lineHeight: '50px' }}>
                                {gls.map((item, index) => {
                                    return (
                                        <p key={index} style={{ display: 'flex', justifyContent: 'space-between' }}><span style={{ whiteSpace: 'nowrap', textOverflow: 'ellipsis', overflow: 'hidden', display: 'inline-block', width: '55%' }}>{item.title}</span><span>{item.date}</span></p>
                                    )
                                })}
                            </div>
                        </div>
                    </div>
                </div>
                <div style={{ background: 'white', width: '580px' }}>
                    <div style={{ padding: '20px', height: '5%', width: '100%', borderBottom: '2px solid rgb(240,240,240)' }}>
                        <h2>我的日程</h2>
                    </div>
                    <div style={{ fontSize: '20px', width: '100%', height: '40%', borderBottom: '2px solid rgb(240,240,240)' }}>
                        <Calendar
                            headerRender={headerRender}
                            onChange={(date: Dayjs) => {
                                console.log(date);
                            }} fullscreen={false} />
                    </div>
                    <div style={{ width: '100%', padding: '20px', fontSize: '18px' }}>
                        <p style={{ marginBottom: '10px' }}>工作内容</p>
                        <div style={{ padding: '20px', height: '200px', border: '1px solid rgb(240,240,240)' }}>
                            <p style={{ marginBottom: '10px' }}>排班日程</p>
                            <div style={{ justifyContent: 'space-between', display: 'flex', flexWrap: 'wrap', width: '100%', height: '100%' }}>
                                <div style={{ height: '30%', padding: '10px', background: '#e7f5ff', width: '45%', }}>
                                    <p>上午&nbsp;&nbsp;08:00-11:30</p>
                                </div>
                                <div style={{ height: '30%', padding: '10px', background: '#e7f5ff', width: '45%', }}>
                                    <p>下午&nbsp;&nbsp;14:00-17:30</p>
                                </div>
                                <div style={{ height: '30%', padding: '10px', background: '#e7f5ff', width: '45%', }}>
                                    <p>上午&nbsp;&nbsp;18:00-21:00</p>
                                </div>
                            </div>
                        </div>
                        <div style={{ marginTop: '20px', padding: '20px', minHeight: '200px', border: '1px solid rgb(240,240,240)' }}>
                            <p style={{ marginBottom: '10px' }}>会诊日程</p>
                            <div style={{ overflowY: 'auto', maxHeight: '400px', width: '100%' }}>
                                <div style={{ lineHeight: '35px', marginTop: '10px', padding: '10px', background: '#e7f5ff', width: '100%', }}>
                                    <p>会议主题：冠心病讨论研究第3次会议</p>
                                    <p>会议时间：2024-07-25&nbsp;14:30:00</p>
                                    <p>会议方式：线上</p>
                                </div>
                                <div style={{ lineHeight: '35px', marginTop: '10px', padding: '10px', background: '#e7f5ff', width: '100%', }}>
                                    <p>会议主题：关于第十六号手术讨论研究会议</p>
                                    <p>会议时间：2024-07-25&nbsp;17:00:00</p>
                                    <p>会议方式：线下</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </>
    );
}

export default Home;